<template>
  <div>
    <div slot="header" class="clearfix">
      <span>物料信息</span>
      <el-button type="primary" @click="fenxi" style="margin-left: 20px">分析</el-button>
      <el-button type="success" @click="suoding">锁定物料</el-button>
      <el-button type="info" @click="shifang">释放物料</el-button>
    </div>
    <div class="info-container">
      <div class="info-item">
        <span>已锁定套数:</span>
        <span class="content">{{ lockedKits }}</span>
      </div>
      <div class="info-item">
        <span>可锁定套数:</span>
        <span class="content">{{ lockableKits }}</span>
      </div>
      <div class="info-item">
        <span>缺料套数:</span>
        <span class="content">{{ shortageKits }}</span>
      </div>
    </div>
    <el-table border v-if="refreshTable" v-loading="loading" :data="matList" row-key="lineId" :row-class-name="tableRowClassName">
      <el-table-column label="产品/物料名称" width="200" align="left" prop="productName" :show-overflow-tooltip="true"/>
      <el-table-column label="产品/物料编号" width="140" align="center" prop="productCode" :show-overflow-tooltip="true"/>
      <el-table-column label="物料类型" width="80" align="center" prop="itemOrProduct" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct"/>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" width="140" align="center" prop="bomSpc" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
      <el-table-column label="计划数量" align="center" prop="used"/>
      <el-table-column label="可用库存数量" align="center" prop="quantityOnhand">
        <template slot-scope="scope">
          <el-tag type="danger">{{ (scope.row.quantityOnhand - scope.row.preOccupied).toFixed(2) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="锁定数量" align="center" prop="quantity"/>
      <el-table-column label="缺料数量" align="center" prop="quantityOnhand">
        <template slot-scope="scope">
          <el-tag type="danger">{{
              parseFloat(
                (scope.row.quantityOnhand - scope.row.preOccupied - scope.row.used + scope.row.quantity).toFixed(2)
              ) > 0
                ? 0
                : Math.abs(
                  parseFloat(
                    (scope.row.quantityOnhand - scope.row.preOccupied - scope.row.used + scope.row.quantity).toFixed(2)
                  )
                )
            }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { fenxi, shifang, suoding } from "@/api/mes/pro/analysis";
import { listAnalysisLine } from "@/api/mes/pro/analysisline";

export default {
  name: 'AnalysisBom',
  dicts: ['mes_item_product'],
  data() {
    return {
      lockedKits: this.kaLockedKits,
      lockableKits: 0,
      shortageKits: 0,
      itemId: undefined,
      // 重新渲染表格状态
      refreshTable: true,
      // 遮罩层
      loading: true,
      // 生产工单BOM组成表格数据
      matList: [],
      showFlag: false,
      // 查询参数
      queryParams: {
        planIds: null,
        kaId: null
      }
    };
  },
  props: {
    planIds: undefined,
    optType: undefined,
    kaId: undefined,
    kaLockedKits: undefined,
    planQuantity: undefined,
  },

  watch: {
    'planIds': function (newValue, oldValue) {
      if (newValue !== oldValue) {
        this.getAnalysisList();
      }
    },
    'kaId': function (newValue, oldValue) {
      if (newValue !== oldValue) {
        this.getAnalysisList();
      }
    }
  },

  created() {
    this.getAnalysisList();
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      if (row.used > (row.quantityOnhand + row.preOccupied)) {
        return 'warning-row';
      }
      return '';
    },
    /** 查询生产工单BOM组成列表 */
    getAnalysisList() {
      this.loading = true;
      this.queryParams.kaId = this.kaId;
      listAnalysisLine(this.queryParams).then(response => {
        this.matList = response.rows;
        this.lockedKits = 0;
        this.lockableKits = 0;
        this.shortageKits = 0;
        if (response.rows.length > 0) {
          this.lockedKits = response.rows[ 0 ].lockedKits;
          this.planQuantity = response.rows[ 0 ].planQuantity;

          if (this.planQuantity > 0) {
            const maxKitList = this.matList.map(item => {
              const availableQty = (item.quantityOnhand || 0) - (item.preOccupied || 0);
              const usedPerKit = item.used / this.planQuantity;

              // 防止除以 0
              if (!usedPerKit || usedPerKit <= 0) return Number.MAX_SAFE_INTEGER;

              // 可支持的最大工单数
              return Math.floor(availableQty / usedPerKit);
            });

            const minSupportableKits = Math.min(...maxKitList);

            // 剩余可锁的数量
            const remainKits = this.planQuantity - this.lockedKits;

            // 实际可锁
            this.lockableKits = Math.max(0, Math.min(minSupportableKits, remainKits));

            // 缺料数
            this.shortageKits = this.planQuantity - this.lockedKits - this.lockableKits;
          }
        }

        this.loading = false;
      });

    },

    fenxi() {
      fenxi(this.kaId).then(response => {
        this.matList = response.data;
        if (this.matList.length > 0 && this.planQuantity > 0) {
          const maxKitList = this.matList.map(item => {
            const availableQty = (item.quantityOnhand || 0) - (item.preOccupied || 0);
            const usedPerKit = item.used / this.planQuantity;

            // 防止除以0或无效数据
            if (usedPerKit <= 0) return Number.MAX_SAFE_INTEGER;

            item.quantity = this.lockedKits * usedPerKit;

            return Math.floor(availableQty / usedPerKit);
          });

          // 找出所有物料中可支持的最小工单数
          const minSupportableKits = Math.min(...maxKitList);

          // 实际可锁的工单数 = min(可支持的最大工单数, 剩余可锁的工单数)
          this.lockableKits = Math.min(minSupportableKits, this.planQuantity - this.lockedKits);

          // 缺料工单数 = 总计划 - 已锁 - 当前可锁
          this.shortageKits = this.planQuantity - this.lockedKits - this.lockableKits;
        }

        this.loading = false;
      });
    },

    suoding({row, rowIndex}) {
      suoding(this.kaId).then(response => {
        this.getAnalysisList();
        this.$emit('refresh-list');
      });
    },

    shifang({row, rowIndex}) {
      shifang(this.kaId).then(response => {
        this.getAnalysisList();
        this.$emit('refresh-list');
      });
    },
  }
};
</script>
<style scoped>
.info-container {
  line-height: 40px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.info-item {
  width: 30%; /* Adjust width as needed */
  margin-bottom: 10px;
}

.info-item span {
  margin-left: 10px;
}

.info-item span:first-child {
  font-family: '苹方 常规', '苹方', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  color: #262626;
  text-align: left;
  line-height: 20px;
  display: inline-block;
}

.content {
  color: #8c8c8c;
  text-align: left;
}
</style>
